package com.dormitory.management.system.service.impl;



import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dormitory.management.system.DAO.UpLoadWeekCheckExcelFileDao;
import com.dormitory.management.system.entity.*;
import com.dormitory.management.system.enums.UserEnum;
import com.dormitory.management.system.listener.UpLoadWeekCheckExcelFileListener;
import com.dormitory.management.system.mapper.*;
import com.dormitory.management.system.req.WeekCheckPageReq;
import com.dormitory.management.system.req.WeekCheckSaveReq;
import com.dormitory.management.system.resp.WeekCheckPageResp;
import com.dormitory.management.system.service.UserService;
import com.dormitory.management.system.service.WeekCheckService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dormitory.managemnet.util.core.Result;
import com.dormitory.managemnet.util.utils.BeanUtil;
import com.dormitory.managemnet.util.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 周例查表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-12-17
 */
@Service
public class WeekCheckServiceImpl extends ServiceImpl<WeekCheckMapper, WeekCheck> implements WeekCheckService {


    @Autowired
    private UserService userService;
    @Autowired
    private WeekCheckService weekCheckService;
    @Autowired
    private HousemasterMapper housemasterMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    UpLoadWeekCheckExcelFileDao upLoadExcelFileDao;

    public int scoreToGrade(long roomId,int score,int week){
        LambdaQueryWrapper<WeekCheck> query = Wrappers.lambdaQuery();
        query.eq(WeekCheck::getRoomId, roomId)
                .lt(WeekCheck::getWeek,week);
        List<WeekCheck> list = weekCheckService.list(query);

        List scoreList = list.stream().map(WeekCheck::getScore).collect(Collectors.toList());
        int sum = 0;
        double finalScore = 0.0;
        if(scoreList.size()==0) finalScore = score;
        else{
            for(int i = 0; i < scoreList.size();i++) sum += list.get(i).getScore();
            finalScore = 0.5*sum/scoreList.size()+0.5*score;}
        if(finalScore>=90)return 5;
        else if(finalScore<90&&finalScore>=80)return 4;
        else if(finalScore<80&&finalScore>=70)return 3;
        else if(finalScore<70&&finalScore>=60)return 2;
        else return 1;
    }

    @Override
    public Result importWeekCheckByExcel(String username,MultipartFile file) throws IOException {
        if (!file.getResource().exists()){
            return Result.error("传入文件没有收到");
        }
        if (!"xlsx".equals(file.getOriginalFilename().split("\\.")[1])){
            return Result.error("请传入.xlsx格式文件");
        }
        /**
         * 通过阿里巴巴的EasyExcel进行excel文件和题库id的上传存储进数据库
         * UpLoadExcelFileListener监听器
         */
        EasyExcel.read(file.getInputStream(), WeekCheckExcel.class, new UpLoadWeekCheckExcelFileListener(upLoadExcelFileDao,username)).sheet().doRead();
        return Result.success("excel导入成功");
    }

    @Override
    public IPage<WeekCheckPageResp> getPage(WeekCheckPageReq req) {
        if (userService.getRoleKey(req.getUserName()).equals(UserEnum.USER_HOUSEMASTER.getRoleKey())) {
            //是宿管
            Housemaster housemaster = housemasterMapper.selectOne(new QueryWrapper<Housemaster>().lambda().eq(Housemaster::getIdentityCard, req.getUserName()));
            //取得宿管管理的楼栋
            Building building = buildingMapper.selectOne(new QueryWrapper<Building>().lambda().eq(Building::getId,housemaster.getBuildingId()));
            Page<WeekCheckPageResp> page = new Page<>(req.getPageCurrent(),req.getPageSize());
            QueryWrapper<WeekCheckPageResp> query = new QueryWrapper<>();
            query.eq(housemaster.getBuildingId() != null,"housemaster.building_id",housemaster.getBuildingId())
                    .eq(housemaster.getIdentityCard() != null,"housemaster.identity_card",req.getUserName())
                    .like(req.getRoomId() != null,"room_id",req.getRoomId())
                    .eq("housemaster.status_id",0)
                    .eq("week_check.status_id",0)
                    .like(req.getWeek() != 0,"week", req.getWeek());
            return this.baseMapper.getWeekCheckPageHouseMaster(page, query);

        }else if (userService.getRoleKey(req.getUserName()).equals(UserEnum.USER_STUDENT.getRoleKey())) {
            //是学生
            Student student = studentMapper.selectOne(new QueryWrapper<Student>().lambda().eq(Student::getStuId,req.getUserName()));
            Room room = roomMapper.selectOne(new QueryWrapper<Room>().lambda().eq(Room::getId,student.getRoomId()));
            Page<WeekCheckPageResp> page = new Page<>(req.getPageCurrent(),req.getPageSize());
            QueryWrapper<WeekCheckPageResp> query = new QueryWrapper<>();
            query.eq(student.getRoomId() != null,"room.id",student.getRoomId())
                    .eq(student.getStuId() != null,"student.stu_id",req.getUserName())
                    .eq("student.status_id",0)
                    .eq("week_check.status_id",0)
                    .like(req.getWeek() != 0,"week", req.getWeek());
            return this.baseMapper.getWeekCheckPageStudent(page, query);
        }else if (userService.getRoleKey(req.getUserName()).equals(UserEnum.USER_ADMIN.getRoleKey())) {
            //是超级管理员
            Page<WeekCheckPageResp> page = new Page<>(req.getPageCurrent(),req.getPageSize());
            QueryWrapper<WeekCheckPageResp> query = new QueryWrapper<>();
            query.eq("week_check.status_id",0)
                    .like(req.getWeek() != 0,"week", req.getWeek())
                    .eq(req.getRoomId()!=null,"week_check.room_id",req.getRoomId());
            return this.baseMapper.getWeekCheckPageUser(page, query);
        }else return null;
    }

    @Override
    public boolean save(WeekCheckSaveReq req){
        return this.baseMapper.insert(BeanUtil.copyProperties(req,WeekCheck.class))>0;
    }

    @Override
    public List<Integer> count(String username) {
        /*QueryWrapper<WeekCheck> query1 = new QueryWrapper<>();
        query1.between("week_check.gmt_create",
                DateUtil.getBeginDayOfLastWeek().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
                DateUtil.getEndDayOfLastWeek().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        System.out.println(this.baseMapper.selectList(query1));*/
        List list = new ArrayList();
        for(int i= 1;i<=5;i++){
            QueryWrapper<Integer> query = new QueryWrapper<>();
            query.eq("housemaster.identity_card", username)
                    .eq("housemaster.status_id", 0)
                    .eq("week_check.status_id", 0)
                    .eq("week_check.grade", i)
                    .between("week_check.gmt_create",
                            DateUtil.getBeginDayOfLastWeek().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
                            DateUtil.getEndDayOfLastWeek().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            list.add(this.baseMapper.count(query));
        }
        return list;
    }



}